package com.lagou.java;

import io.netty.channel.*;

import java.util.concurrent.Callable;

/**
 * @Classname UserClientHandler
 * @Description TODO
 * @Date 2020/7/22 13:20
 * @Created by pc
 */
//public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {
public class UserClientHandler extends ChannelInboundHandlerAdapter {

    private ChannelHandlerContext context;
//    private Channel channel;

    private String result;
    private String para;
    private RpcRequest data;

    public void closeConnnection () {
        context.channel().close();
        context.close();
        Thread.currentThread().destroy();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    // 收到数据, 唤醒线程
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result = msg.toString();
//        notify();
    }



    // 处理连接异常
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Channel incoming = ctx.channel();
        if(!incoming.isActive())
            System.out.println("SimpleClient:" + incoming.remoteAddress()
                    + "异常");

        cause.printStackTrace();
        ctx.close();
    }

    // 写出数据, 开始等待唤醒
//    @Override
//    public synchronized Object call() throws Exception {
////        context.writeAndFlush(para);
//        System.out.println("--->>> from：" + context.channel().localAddress() + "--to--"
//                + context.channel().remoteAddress()
//                + ", send message :" + data.toString());
//        channel.writeAndFlush(data);;
//        wait();
//        return result;
//    }

    public void setPara(String para) {
        this.para = para;
    }

    public void setData(RpcRequest data) {
        this.data = data;
    }
}
